package edu.jxufe.nb112.common.web.servlet.tags;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.RandomStringGenerator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import java.io.IOException;

/**
 * 防止crsf攻击
 */
public class CRSFTokenTag implements Tag {

    private PageContext pageContext;
    private Tag parentTag;
    /**
     * 页面标识符
     */
    private String id;


    public void setPageContext(PageContext pageContext) {
        this.pageContext=pageContext;
    }

    public void setParent(Tag tag) {
        this.parentTag=tag;
    }

    public Tag getParent() {
        return parentTag;
    }

    public int doStartTag() throws JspException {
        return Tag.SKIP_BODY;
    }


    public int doEndTag() throws JspException {
        String randomCRSFToken = generateRandomCRSFToken(pageContext.getSession(),this.id);
               JspWriter jspWriter =pageContext.getOut();
        try {
            jspWriter.print("<input id=\""+this.id+"\" type=\"hidden\" name=\"CRSFToken\" value=\"" +randomCRSFToken+ "\" />");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Tag.EVAL_PAGE;
    }

    /**
     * 校验token是否合法
     * @param request
     * @param id
     * @return
     */
    public static boolean validate(HttpServletRequest request,String id){
        String  answer = request.getParameter("CRSFToken");
        if(StringUtils.isNoneEmpty(answer)){
            String randomCRSFToken = (String) request.getSession().getAttribute("_CRSFToken_"+id);
            if(answer.equals(randomCRSFToken)) {
                request.getSession().removeAttribute("_CRSFToken_"+id);
                return true;
            }
        }
        return false;

    }

    /**
     * 产生session
     * @param httpSession
     * @param id
     * @return
     */
    public static String generateRandomCRSFToken(HttpSession httpSession,String id){
        RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange('a', 'z').build();
        String randomCRSFToken = generator.generate(6);
        httpSession.setAttribute("_CRSFToken_"+id,randomCRSFToken);
        return randomCRSFToken;
    }

    public void release() {

    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }


}
